#! /usr/bin/env python
# coding:utf-8

"""
Usage:
    ed3-remote <host> <index>
"""

import os
import io
import sh
import sys
import docopt
import shutil
import datetime

def rmtree_date(root, date):
    for year in os.listdir(root):
        for month in os.listdir(os.path.join(root, year)):
            if int(year) * 12 + int(month) < date:
                path = os.path.join(root, year, month)
                print 'rmtree %s ...' % path
                sys.stdout.flush()
                shutil.rmtree(path)

def package_server(proj_root, pkg_root, index, user, password):
    sql_root = os.path.join(pkg_root, 'ed3.sql')

    if os.path.exists(sql_root):
        shutil.rmtree(sql_root)
    os.makedirs(sql_root)

    mysqldump = sh.Command('/usr/local/mysql/bin/mysqldump')
    for db in ['db_game', 'db_mail', 'db_expd', 'db_pays']:
        db_name = db + '%02d' % index
        file = os.path.join(sql_root, db_name + '.sql')
        print 'dump %s to %s ...' % (db_name, file)
	sys.stdout.flush()
        mysqldump('-u' + user, '-p' + password, db_name, _out=file)

    cwd = os.path.join(pkg_root, 'ed3.sql')
    tar = os.path.join(pkg_root, 'ed3_db_%02d.tar.gz' % index)
    print 'package %s to %s ...' % (cwd, tar)
    sys.stdout.flush()

    sh.tar.zcf(tar, '.', _cwd=cwd)
    shutil.rmtree(sql_root)

    for server in ('login', 'cache', 'logic', 'logger'):
        path = os.path.join('/data/app%02d/%s/core' % (index, server))
        if os.path.exists(path):
            shutil.rmtree(path)

    cwd = '/data/app%02d' % index
    tar = os.path.join(pkg_root, 'ed3_app_%02d.tar.gz' % index)
    print 'package %s to %s ...' % (cwd, tar)
    sys.stdout.flush()

    sh.tar.zcf(tar, '.', _cwd=cwd)

    exp_root = '/data/wwwroot/exp%02d' % index
    now = datetime.datetime.now()
    date = now.year * 12 + now.month - 2

    rmtree_date(os.path.join(exp_root, 'data/pve'), date)
    rmtree_date(os.path.join(exp_root, 'data/upload'), date)

    tar = os.path.join(pkg_root, 'ed3_exp_%02d.tar.gz' % index)
    print 'package %s ...' % tar
    sys.stdout.flush()

    sh.tar.zcf(tar, '.', _cwd=exp_root)

if __name__ == '__main__':
    opts = docopt.docopt(__doc__)

    conf = {
        'index': int(opts['<index>']),
        'user': 'ed3',
        'password': 'xsj@ed3.good^team*com',
    }

    proj_root = os.path.abspath(os.path.dirname(__file__))
    pkg_root = os.path.join(proj_root, 'ed3.pkg')

    if os.path.exists(pkg_root):
        shutil.rmtree(pkg_root)

    package_server(proj_root, pkg_root, **conf)

    sh.yum('install', '-y', 'sshpass', _out=sys.stdout)

    scp = sh.sshpass.bake('-peQgC4vj61Z', 'scp', '-o', 'StrictHostKeyChecking no', '-v', '-r')
    scp(os.path.join(proj_root, 'ed3.pkg'), 'root@%s:/root/ed3.move' % opts['<host>'], _out=sys.stdout)
